package com.wfl.sampling.web;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.wfl.sampling.aop.NoAuth;
import com.wfl.sampling.entity.*;
import com.wfl.sampling.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.server.ResponseStatusException;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@Slf4j
@RequestMapping("/api/user")
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/email/{email}")
    public User getUserByEmail(@PathVariable String email) {
        User user = userService.findByEmail(email);
        if (user == null) {
            throw new ResponseStatusException(HttpStatus.NOT_FOUND, "User not found");
        }
        return user;
    }

    @GetMapping("/phone/{phone}")
    public User getUserByPhone(@PathVariable String phone) {
        User user = userService.findByPhone(phone);
        if (user == null) {
            throw new ResponseStatusException(HttpStatus.NOT_FOUND, "User not found");
        }
        return user;
    }
    @PostMapping("/login")
    public Map<String, Object> loginUser(@RequestBody User user) {
        Map<String, Object> response = new HashMap<>();

        if (user.getEmail() == null && user.getPhone() == null) {
            throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "请输入有效的邮箱或手机号码");
        }

        User foundUser = (user.getEmail() != null) ? userService.findByEmail(user.getEmail()) : userService.findByPhone(user.getPhone());

        if (foundUser == null) {
            response.put("errorType", "userNotExist");
            response.put("message", "用户不存在");
            return response;
        }

        // Assuming you have a method for hashing passwords.
        boolean passwordMatches = user.getPassword().equals(foundUser.getPassword());
        if (passwordMatches) {
            response.put("success", true);
            response.put("message", "登录成功！");
            response.put("userId", foundUser.getId()); // 返回用户ID
            response.put("userName", foundUser.getUsername()); // 返回用户名
            response.put("useravatar", foundUser.getAvatar()); // 返回用户头像
        } else {
            response.put("errorType", "passwordIncorrect");
            response.put("message", "密码错误");
        }

        return response;
    }


    @PostMapping("/register")
    public Map<String, Boolean> registerUser(@RequestBody User user) {
        if (user.getEmail() == null && user.getPhone() == null) {
            throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Email or phone must be provided");
        }

        if (user.getPassword() == null || user.getPassword().isEmpty()) {
            throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Password must be provided");
        }

        int result = userService.createUser(user);
        Map<String, Boolean> response = new HashMap<>();
        response.put("success", result > 0);
        return response;
    }

    @PostMapping("/updateLastLogin")
    public void updateLastLogin(@RequestBody User user) {
        if (user.getId() == 0) {
            throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "User ID must be provided for update");
        }
        System.out.println(user.getId());
        userService.updateLastLogin(user.getId());
    }

    // Add a global exception handler
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Map<String, Object> handleAllExceptions(Exception ex) {
        Map<String, Object> response = new HashMap<>();
        response.put("message", "An unexpected error occurred");
        // Log the actual exception for debugging purposes
        // e.g. logger.error("Unexpected error occurred", ex);
        return response;
    }

    @GetMapping("/getUserInfo/{userId}")
    public ResponseEntity<User> getUserInfo(@PathVariable int userId) {
        User user = userService.getUserById(userId);
        if (user != null) {
            return ResponseEntity.ok(user);
        } else {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
        }
    }
    @PostMapping("/saveUser")
    public void saveUserInfoById(@RequestBody User user){
        System.out.println("Received user data: " + user);
        userService.saveUserInfoById(user);
    }
    /**
     * 查询关注/被关注人数和id列表  还有一些信息
     */
    @GetMapping("/getUserRelationship")
    public HashMap<String, ArrayList<User>> selectUserRelationship(@RequestParam(name = "userId") Integer userId){

        return  userService.getUserRelationship(userId);
    }
    //关注  传入当前用户id和关注者的id
    @PostMapping("/followOn/{userId}")
    public String followOnUser(@PathVariable int userId,@RequestParam(name = "followUser") Integer followUser) {
        return userService.followOnUser(userId,followUser);
    }
    //取关
    @PostMapping("/followOff/{userId}")
    public String followOffUser(@PathVariable int userId,@RequestParam(name = "followUser") Integer followUser) {
        return userService.followOffUser(userId,followUser);
    }
    //用户之间建立对话联系
    @PostMapping("/conversionBuilding")
    public String conversionBuilding(@RequestParam(name = "userId") Integer userId,
                                     @RequestParam(name = "otherId") Integer otherId) {
        return userService.conversionBuilding(userId,otherId);
    }
    //查询历史对话消息  传入当前用户id和对话的用户id
    @GetMapping("/getUserMessage")
    public ArrayList<UserMessageDo> getUserMessage(@RequestParam(name = "userId") Integer userId,
                                                   @RequestParam(name = "otherId") Integer otherId){
        return userService.getUserMessage(userId,otherId);
    }
    //保存对话消息
    @PostMapping("/saveConversion")
    public String saveConversionMessage(@RequestParam(name = "userId") Integer userId,
                                        @RequestParam(name = "otherId") Integer otherId,
                                        @RequestParam(name = "message") String message){
        return userService.saveConversionMessage(userId,otherId,message);
    }
    //查询当前用户的所有消息列表
    @GetMapping("/getMessageList")
    public List<MessageListDo> getMessageList(@RequestParam(name = "userId") Integer userId){
        return userService.getMessageList(userId);
    }

    //前端第一步，调用weXin.login获得code，
    @NoAuth
    @GetMapping("/getSessionId")
    public Result getSessionId(String code){
        return userService.getSessionId(code);
    }
    @NoAuth
    @GetMapping("/userLogin")
    public Result login(String sessionId){
        Result result = userService.getUserIdByOpenId(sessionId);
        if(result==null)
            return Result.error("未注册");
        else return result;
    }
    @NoAuth
    @PostMapping("/authLogin")
    public Result authLogin(@RequestBody WXAuth wxAuth){
        Result result = null;
        try {
            result = userService.authLogin(wxAuth);
        } catch (Exception e) {
            log.info("authLogin方法有问题");
        }
        log.info("{}",result);
        return result;
    }

    @NoAuth
    @PostMapping("/wxLogin")
    public Result weChatLogin(@RequestBody User user){
        return userService.weChatLogin(user);
    }
}
